<?php
// +----------------------------------------------------------------------
// | 云南喵云科技
// +----------------------------------------------------------------------
// | 官方网站: https://www.meoyun.com
// +----------------------------------------------------------------------
// | Author: 喵大大
// +----------------------------------------------------------------------
// | Email: mmteen@sina.com
// +----------------------------------------------------------------------
// | Date: 2021/10/29/029
// +----------------------------------------------------------------------
// | Time: 12:02
// +----------------------------------------------------------------------
namespace App\WebSocket;


use App\Model\UserModel;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Redis\Redis;
use EasySwoole\Socket\AbstractInterface\Controller;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Task\TaskManager;

/**
 * Class Index
 * 此类是默认的 websocket 消息解析后访问的 控制器
 */
class Index extends Controller
{
    //发送消息给客服工作人员
    public function sendWorker()
    {
        $redis = new Redis(new RedisConfig());

        $param = $this->caller()->getArgs();

        $user_fd = $param["user_fd"];
        $worker_fd = $redis->get("worker_" . $param["worker_uid"]);

        $data = [
            "type" => "message",
            "user_fd" => $user_fd,
            "worker_uid" => $param["worker_uid"],
            "content" => $param["content"]
        ];

        $this->taskMessage($user_fd, $worker_fd, $data);
    }

    //发送消息给用户
    public function sendUser()
    {
        $param = $this->caller()->getArgs();

        $redis = new Redis(new RedisConfig());
        $worker_fd = $redis->get("user_" . $param["worker_uid"]);
        $user_fd = $param["user_fd"];

        $user = UserModel::create()->where(["id" => $param["worker_uid"]])->get();
        $data = [
            "type" => "message",
            "user" => $user,
            "user_fd" => $user_fd,
            "content" => $param["content"]
        ];

        $this->taskMessage($worker_fd, $user_fd, $data);
    }

    //异步投递消息
    public function taskMessage($from_fd, $to_fd, $data)
    {
        TaskManager::getInstance()->async(function () use ($from_fd, $to_fd, $data) {
            $server = ServerManager::getInstance()->getSwooleServer();
            $server->push($to_fd, json_encode($data));//发送消息
        });
    }

    //ping，保持连接
    public function heartbeat()
    {
        $param = $this->caller()->getArgs();

        $server = ServerManager::getInstance()->getSwooleServer();

        $data = [
            'content' => 'ping success'
        ];

        $server->push($param["user_fd"], json_encode($data));//发送消息
    }
}